#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
static int evtdev = -1;
static int fbdev = -1;
static struct timeval boot_time = {};
int screen_w = 0, screen_h = 0;
int can_w = 0, can_h = 0;
static int events = -1;
static int fb = -1;
static int dispinfo = -1;
extern int open(const char *path, int flags, ...) ;
uint32_t NDL_GetTicks() {
  struct timeval tv;
  gettimeofday(&tv,NULL);
  long seconds = tv.tv_sec - boot_time.tv_sec;
  return seconds << 8;
   
}

int NDL_PollEvent(char *buf, int len) {
  return read(events,buf,len);
}

void NDL_OpenCanvas(int *w, int *h) {
    char buf[256];
    read(dispinfo,buf,256);
    char name[24];
    int num;
    char *token;
    token = strtok(buf, "\n");
    /* 继续获取其他的子字符串 */
    while( token != NULL ) {
      sscanf(token,"%s %d\n",name,&num);
      // printf("name = %s,num = %d\n",name,num);
      if (strcmp(name,"WIDTH:")==0)
      {
        screen_w = num;
        // printf("WIDTH = %d\n",screen_w);
      }
      else if(strcmp(name,"HEIGHT:")==0)
      {
        screen_h = num;
        // printf("HEIGHT = %d\n",screen_h);
      }
      token = strtok(NULL, "\n");
    }
    if (*w ==0 && *h == 0)
    {
      can_w = screen_w;can_h = screen_h;
      *w    = screen_w;*h    = screen_h;
    // printf("w = %d  h = %d\n",*w,*h);
    }
    else 
    {
      if (*w > screen_w)
      {
        can_w = screen_w;
      }
      else{
        can_w = *w;
      }
      if (*h > screen_h)
      {
        can_h = screen_h;
      }
      else{
        can_w = *h;
      }
    }
  // }
}
void NDL_DrawRect(uint32_t *pixels, int x, int y, int w, int h) {
  size_t xy,wh;
  // if (y+h > 300 || x+w > 400)
  // {
    
  // }
  
  xy =( x << 12) + y;
  wh =( h << 12) + w;
  // for (size_t i = 0; i < h; i++)
  // {
    // lseek(fb,(x+(y+i)*screen_w)*(sizeof(uint32_t)),0);  
  int offset = lseek(fb,xy,0);  
    // memset(&buf,0,1600); 
    // memcpy(&buf,pixels+i*w,w*sizeof(uint32_t));
    // write(fb,pixels+i*w,w);
  write(fb,pixels,wh);
  // }
}

void NDL_OpenAudio(int freq, int channels, int samples) {
}

void NDL_CloseAudio() {
}

int NDL_PlayAudio(void *buf, int len) {
  return 0;
}

int NDL_QueryAudio() {
  return 0;
}

int NDL_Init(uint32_t flags) {
  events = open("/dev/events",0);
  dispinfo = open("/proc/dispinfo",0);
  fb = open("/dev/fb", 0);
  gettimeofday(&boot_time,NULL);
  return 0;
}

void NDL_Quit() {
}

void printf_SDL(char * func_name)
{
  printf("function %s but cannt realization\n",func_name);
}

void printf_num(char * name ,int num)
{
  printf("name = %s ,num = %d\n",name,num);
}